﻿namespace CsvViewer
{
    using System;
    using System.Data;
    using System.IO;
    using System.Text;
    using System.Windows;
    using Microsoft.Win32;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MenuOpenClick(object sender, RoutedEventArgs e)
        {
            var ofd = new OpenFileDialog()
                          {
                              Filter = "csv|*.csv",
                              Multiselect = false
                          };
            var result = ofd.ShowDialog(this);
            if(result.HasValue && result.Value)
            {
                var dt = datagrid.DataContext as DataTable;
                if (dt != null)
                    dt.Dispose();

                datagrid.DataContext = null;

                LoadFile(ofd.FileName);
            }

        }
        private void MenuSaveClick(object sender, RoutedEventArgs e)
        {
            var dt = datagrid.DataContext as DataTable;
            if(dt == null) return;

            var sfd = new SaveFileDialog() { Filter = "csv|*.csv" };
            var result = sfd.ShowDialog(this);
            if(!result.HasValue || !result.Value) return;
            
            dt.AcceptChanges();

            SaveFile(sfd.FileName, dt.CreateDataReader(), dt.Columns);
        }

        private void MenuCloseClick(object sender, RoutedEventArgs e)
        {
            var dt = datagrid.DataContext as DataTable;
            if(dt!=null)
                dt.Dispose();

            datagrid.DataContext = null;

        }
        private void MenuExitClick(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        void LoadFile(string file)
        {
            if (string.IsNullOrEmpty(file) || !File.Exists(file)) return;

            var lines = File.ReadAllLines(file);
            var header = lines[0];

            var cols = header.Split(new char[] { ';' }, StringSplitOptions.None);

            var dt = new DataTable();
            dt.BeginLoadData();

            for (int i = 0; i < cols.Length; i++)
                dt.Columns.Add(cols[i], typeof (string));

            for(int i=1; i<lines.Length; i++)
            {
                dt.LoadDataRow(
                    lines[i].Split(';'),
                    LoadOption.OverwriteChanges);
            }

            dt.EndLoadData();
            datagrid.DataContext = dt;
        }

        static void SaveFile(string file, IDataReader reader, DataColumnCollection columns)
        {
            using(var fout = new StreamWriter(file, false, Encoding.UTF8))
            {
                var sb = new StringBuilder();
                foreach (DataColumn column in columns)
                    sb.AppendFormat(";{0}",column.ColumnName);

                fout.WriteLine(sb.ToString(1, sb.Length-1));
                sb.Clear();

                var buffer = new string[reader.FieldCount];
                while (reader.Read())
                {
                    reader.GetValues(buffer);
                    fout.WriteLine( string.Join(";", buffer) );
                }
                fout.Flush();
                fout.Close();
            }
        }
    }
}
